cc.Class({
    extends: cc.Component,

    properties: {
        manifestUrl: {
            default: null,
            url: cc.RawAsset
        },
        percent: {
            default: null,
            type: cc.Label
        },
        sizeProgress : cc.ProgressBar,
        fileProgress : cc.ProgressBar
    },

    checkCb: function (event) {
        this.isCheckEnd = true;
        console.log('Code: ' + event.getEventCode());
        switch (event.getEventCode())
        {
            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST://0
                console.log("No local manifest file found, hot update skipped.");
                cc.eventManager.removeListener(this._checkListener);
                this.nextScene();
                break;
            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST://1
            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST://2
                console.log("Fail to download manifest file, hot update skipped.");
                cc.eventManager.removeListener(this._checkListener);
                this.nextScene();
                break;
            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE://5
                console.log("Already up to date with the latest remote version.");
                cc.eventManager.removeListener(this._checkListener);
                this.percent.string += "游戏不需要更新\n";
                this.nextScene();
                break;
            case jsb.EventAssetsManager.NEW_VERSION_FOUND://4
                this._needUpdate = true;
                this.percent.string = '正在更新文件';
                this.sizeProgress.node.active = true;
                this.fileProgress.node.active = true;
                cc.eventManager.removeListener(this._checkListener);
                break;
            default:
                break;
        }
        this.hotUpdate();
    },

    updateCb: function (event) {
        console.log('updateCb:',event.getEventCode())
        var needRestart = false;
        var failed = false;
        switch (event.getEventCode())
        {
            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST://0
                console.log('No local manifest file found, hot update skipped.');
                failed = true;
                break;
            case jsb.EventAssetsManager.UPDATE_PROGRESSION://5
                var percent = event.getPercent();
                var percentByFile = event.getPercentByFile();
                console.log('percent:',percent);
                console.log('percentByFile:',percentByFile);
                var v = (percentByFile*100).toFixed(2)
                this.percent.string = '正在更新文件:'+v+'%';
                this.sizeProgress.progress = percent
                this.fileProgress.progress = percentByFile
                break;
            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST://1
            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST://2
                console.log('Fail to download manifest file, hot update skipped.');
                failed = true;
                break;
            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE://4
                console.log('Already up to date with the latest remote version.');
                failed = true;
                break;
            case jsb.EventAssetsManager.UPDATE_FINISHED:
                console.log('Update finished. ' + event.getMessage());
                this.sizeProgress.progress = 1
                this.fileProgress.progress = 1
                this.percent.string = '游戏资源更新完毕';
                needRestart = true;
                break;
            case jsb.EventAssetsManager.UPDATE_FAILED:
                console.log('Update failed. ' + event.getMessage());

                this._failCount ++;
                if (this._failCount < 5)
                {
                    this._am.downloadFailedAssets();
                }
                else
                {
                    cc.log('Reach maximum fail count, exit update process');
                    this._failCount = 0;
                    failed = true;
                }
                break;
            case jsb.EventAssetsManager.ERROR_UPDATING:
                console.log('Asset update error: ' + event.getAssetId() + ', ' + event.getMessage());
                break;
            case jsb.EventAssetsManager.ERROR_DECOMPRESS:
                console.log(event.getMessage());
                break;
            default:
                break;
        }

        if (failed) {
            cc.eventManager.removeListener(this._updateListener);
        }

        if (needRestart) {
            cc.eventManager.removeListener(this._updateListener);
            // Prepend the manifest's search path
            var searchPaths = jsb.fileUtils.getSearchPaths();
            var newPaths = this._am.getLocalManifest().getSearchPaths();
            Array.prototype.unshift(searchPaths, newPaths);
            cc.sys.localStorage.setItem('HotUpdateSearchPaths', JSON.stringify(searchPaths));

            jsb.fileUtils.setSearchPaths(searchPaths);
            setTimeout(function(){
                cc.game.restart();
            },0.2)
        }
    },

    hotUpdate: function () {
        if (this._am && this._needUpdate) {
            this.percent.string += "开始更新游戏资源...\n";
            this._updateListener = new jsb.EventListenerAssetsManager(this._am, this.updateCb.bind(this));
            cc.eventManager.addListener(this._updateListener, 1);

            this._failCount = 0;
            this._am.update();
        }
    },

    // use this for initialization
    onLoad: function () {
        // Hot update is only available in Native build
        if (!cc.sys.isNative) {
            this.nextScene();
            // cc.director.loadScene("loading");
            return;
        }
        this.isCheckEnd = false;
        
        this.percent.string += "检查游戏资源...\n";
        var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'xygame-asset');
        console.log('Storage path for remote asset : ' + storagePath);
        console.log('Local manifest URL : ' + this.manifestUrl);
        this._am = new jsb.AssetsManager(this.manifestUrl, storagePath);
        this._am.retain();

        this._needUpdate = false;
        if (this._am.getLocalManifest().isLoaded())
        {
            this._checkListener = new jsb.EventListenerAssetsManager(this._am, this.checkCb.bind(this));
            cc.eventManager.addListener(this._checkListener, 1);

            var self = this;
            this.node.runAction(cc.sequence(cc.delayTime(5.0),cc.callFunc(function(){
                self.cancelUpdate();
            })))

            this._am.checkUpdate();
        }
    },

    cancelUpdate : function(){
        if(this.isCheckEnd)
            return;

        cc.eventManager.removeListener(this._checkListener);
        this.nextScene();
    },

    nextScene(){
        // cc.director.loadScene("loading");
        this._am && this._am.release();
        cc.director.loadScene('Main')
    }
});
